package com.onlocation.util;

import android.content.Context;
import android.media.AudioManager;

/**
 * Author: Steve Carrell
 * Date: 5/11/12
 */
public class VolumeUtil {
    public static final int VIBRATE_DURATION = 1000;

    private static AudioManager audioManager = null;

    public static void init() {
        if (audioManager == null) {
            audioManager = (AudioManager) Util.context.getSystemService(Context.AUDIO_SERVICE);
        }
    }
    
    public static Integer getCurrentVolume() {
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
        int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
        if (maxVolume <= 0) {
            return 0;
        } else {
            return (currVolume * 100) / maxVolume;
        }
    }
    
    public static Boolean getCurrentIsVibrate() {
        int setting = audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
        return setting == AudioManager.VIBRATE_SETTING_ON ||
                setting == AudioManager.VIBRATE_SETTING_ONLY_SILENT;
    }
    
    public static void setVolumeAndVibrate(int volume, boolean vibrate) {
        int vibrateSetting = vibrate ? AudioManager.VIBRATE_SETTING_ON : AudioManager.VIBRATE_SETTING_OFF;
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
        if (volume <= 0) {
            volume = 0;
        }
        int newVolume = (new Double(volume / 100.0)).intValue() * maxVolume;
        
        if (newVolume == 0 && vibrate) {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        } else if (newVolume == 0) {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        } else {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        audioManager.setStreamVolume(AudioManager.STREAM_RING, newVolume, 0);
        audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, vibrateSetting);
    }
}
